package com.mes.biz.service.impl;

import java.util.List;

import com.mes.biz.domain.BizProduct;
import com.mes.common.utils.SecurityUtils;
import com.mes.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageInfo;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.framework.cache.UserUtils;
import com.mes.common.core.domain.entity.SysUser;
import com.mes.common.utils.StringUtils;
import com.mes.biz.mapper.BizCustomerMapper;
import com.mes.biz.domain.BizCustomer;
import com.mes.biz.service.BizCustomerService;
import org.springframework.transaction.annotation.Transactional;
import com.mes.common.exception.BizException;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 客户档案Service业务层处理
 * @author hwg
 * @email hwg
 * @date 2023-04-30
 */
@Service
@Transactional(readOnly = true)
public class BizCustomerServiceImpl extends BaseServiceImpl<BizCustomerMapper, BizCustomer> implements BizCustomerService {

    private static final Logger log = LoggerFactory.getLogger(BizCustomerServiceImpl.class);
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 获取单条数据
     * @param bizCustomer 客户档案
     * @return 客户档案
     */
    @Override
    public BizCustomer get(BizCustomer bizCustomer) {
        BizCustomer dto = super.get(bizCustomer);
        if (StringUtils.isNotEmpty(dto.getCustomernan())){
            SysUser sysUser = UserUtils.getSysUser(dto.getCustomernan());
			if (null != sysUser){
				dto.setCustomernanName(sysUser.getName());
			}
        }
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 客户档案id
     * @return 客户档案
     */
    @Override
    public BizCustomer get(String id) {
        BizCustomer dto = super.get(id);
        if (dto != null  && StringUtils.isNotEmpty(dto.getCustomernan())){
			SysUser sysUser = UserUtils.getSysUser(dto.getCustomernan());
			if (null != sysUser){
				dto.setCustomernanName(sysUser.getName());
			}
		}
        return dto;
    }

    /**
     * 查询客户档案列表
     * @param bizCustomer 客户档案
     * @return 客户档案
     */
    @Override
    public List<BizCustomer> findList(BizCustomer bizCustomer) {
		List<BizCustomer> bizCustomerList = super.findList(bizCustomer);
		if (!CollectionUtils.isEmpty(bizCustomerList)) {
			bizCustomerList.stream().forEach(dto -> {
				if (StringUtils.isNotEmpty(dto.getCustomernan())){
					SysUser sysUser = UserUtils.getSysUser(dto.getCustomernan());
					if (null != sysUser){
						dto.setCustomernanName(sysUser.getName());
					}
				}
			});
		}
        return bizCustomerList;
    }

    /**
     * 分页查询客户档案列表
     * @param bizCustomer 客户档案
     * @return 客户档案
     */
    @Override
    public PageInfo<BizCustomer> findPage(BizCustomer bizCustomer) {
		PageInfo<BizCustomer> page = super.findPage(bizCustomer);
		if (!CollectionUtils.isEmpty(page.getList())) {
            page.getList().stream().forEach(dto -> {
				if (StringUtils.isNotEmpty(dto.getCustomernan())){
					SysUser sysUser = UserUtils.getSysUser(dto.getCustomernan());
					if (null != sysUser){
						dto.setCustomernanName(sysUser.getName());
					}
				}
            });
        }
        return page;
    }

    /**
     * 保存客户档案
     * @param bizCustomer
     * @return 结果
     */
    @Override
    public boolean save(BizCustomer bizCustomer) {
        checkCustomerNameUnique(bizCustomer);
        if (StringUtils.isNotEmpty(bizCustomer.getPhone())){
            SysUser user = new SysUser();
            String userId=null;
            if (StringUtils.isNotEmpty(bizCustomer.getUserId())){
                user = sysUserService.get(bizCustomer.getUserId());
                user.setPhonenumber(bizCustomer.getPhone());
                user.setUserName(bizCustomer.getPhone());
                userId=bizCustomer.getUserId();
                sysUserService.save(user);
            }else {
                user = new SysUser();
                user.setTenantId(SecurityUtils.getTenantId());
                user.setPhonenumber(bizCustomer.getPhone());
                user.setUserName(bizCustomer.getPhone());
                user.setUserType(BaseEntity.CUSTOMER_USER);
                user.setStatus(BaseEntity.WAIT_HAHDLE);
                sysUserService.save(user);
                String id = user.getId();
                bizCustomer.setUserId(id);
                userId=id;
            }
            List<SysUser> sysUserList = sysUserService.selectUserByPhoneWithUserId(bizCustomer.getPhone(), userId);
            if (sysUserList !=null && sysUserList.size()>0){
                throw new BizException("客户手机号已存在，请重新输入！");
            }

        }else {
            if (StringUtils.isNotEmpty(bizCustomer.getUserId())){
             sysUserService.deleteUserById(bizCustomer.getUserId());
            }
        }
        return super.save(bizCustomer);
    }

    /**
     * 校验客户名称的唯一性
     * @param bizCustomer
     */
    @Override
    public void checkCustomerNameUnique(BizCustomer bizCustomer) {
        BizCustomer bizCustomerUnique = new BizCustomer();
        bizCustomerUnique.setNotEqualId(bizCustomer.getId());
        bizCustomerUnique.setCustomerName(bizCustomer.getCustomerName());
        if (!CollectionUtils.isEmpty(mapper.findListWithUnique(bizCustomerUnique))) {
            throw new BizException("客户名称已存在，请重新输入！");
        }
    }

    /**
     * 删除客户档案信息
     * @param bizCustomer
     * @return 结果
     */
    @Override
    public boolean remove(BizCustomer bizCustomer) {

        return super.remove(bizCustomer);
    }

    /**
     * 批量删除客户档案
     * @param ids 需要删除的客户档案ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizCustomerByIds(String[] ids) {
        if (ids !=null){
            for (String id :ids){
                //判断是否存在单据明细中
                BizCustomer bizCustomer = super.get(id);
//                long l = mapper.checkInDetailByProductId(bizProduct.getId(), bizProduct.getProductCode());
//                if (l>0){
//                    throw new BizException("产品编号"+bizProduct.getProductCode()+"已存在单据中，不能删除");
//                }
            }
        }

        //先删除这个客户创建过的用户
        List<String> userIdByIds = mapper.getUserIdByIds(ids);
        if (userIdByIds != null && userIdByIds.size()>0){
            String[] userIds =(String[]) userIdByIds.toArray();
            sysUserService.deleteUserByIds(userIds);
        }
        return mapper.deleteBizCustomerByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public BizCustomer getCustomerByUserId(String userId) {

        return mapper.getCustomerByUserId(userId);
    }

}
